package com.qyt.hotel.controller;

import com.qyt.hotel.entity.Result;
import com.qyt.hotel.entity.User;
import com.qyt.hotel.entity.StatusCode;
import com.qyt.hotel.service.CodeService;
import com.qyt.hotel.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.UUID;

@CrossOrigin(origins = "*")
@RestController
@RequestMapping(value = "/user")
public class LoginController {

    @Resource
    private UserService userService;

    @Autowired
    private CodeService codeService;

    @GetMapping("/login")
    public Result login(User user, @RequestParam String codeToken, @RequestParam String code) {
        // 检验验证码
        boolean valid = codeService.validCode(codeToken, code);
        if (!valid) return new Result("验证码错误", false, null, StatusCode.ERROR, null);
        User user1 = userService.checkUser(user);
        String token = UUID.randomUUID().toString();
        if (null != user1) {
            return new Result("登录成功", true, token, StatusCode.OK, null);
        } else {
            String loginId = userService.getLoginId(user);
            if (null == loginId) {
                return new Result("用户名错误", false, token, StatusCode.ERROR, null);
            } else {
                String loginPwd = userService.getLoginPwd(user);
                if (loginPwd == null) {
                    return new Result("密码错误", false, token, StatusCode.ERROR, null);
                } else {
                    return new Result("登录成功", false, token, StatusCode.ERROR, null);
                }
            }
        }
    }

    @GetMapping("/registry")
    public Result registry(User user) {
        try {
            userService.registry(user);
            return Result.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.ERROR;
    }

    @GetMapping("/getOne")
    public User getOne(User user) {
        return userService.getOne(user);
    }

    @GetMapping("/code/{codeToken}/{code}")
    public Result<?> code(@PathVariable("codeToken") String codeToken, @PathVariable("code") String code) {
        try {
            codeService.saveCode(codeToken, code);
            return Result.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.ERROR;
    }
}
